package com.yc.hwc.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.http.MediaType;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

import javax.validation.Valid;

import com.yc.hwc.bean.Result;
import com.yc.hwc.biz.BaseBiz;
import com.yc.hwc.biz.BizException;
import com.yc.jpa.bean.PageBean;
import com.yc.util.Utils;

public class BaseAction<E> {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	protected BaseBiz<E> biz;

	@Autowired
	public void setBiz(BaseBiz<E> biz) {
		this.biz = biz;
	}

	public JpaRepository<E, Long> getDao() {
		return biz.getDao();
	}

	/*
	 * @PostMapping(path = "save", consumes =
	 * MediaType.APPLICATION_FORM_URLENCODED_VALUE) public Result<?> save1(@Valid E
	 * e, Errors es) { return save(e, es); }
	 */

	@PostMapping(path = "save", consumes = MediaType.APPLICATION_JSON_VALUE)
	public Result<?> save1(@RequestBody @Valid E e, Errors es) {
		return save(e, es);
	}

	@PostMapping(path = "save")
	public Result<?> save(@Valid E e, Errors es) {
		logger.debug("" + e);
		logger.debug("" + es);
		try {
			biz.save(e, es);
			return Result.success("保存成功！", e);
		} catch (BizException e1) {
			e1.printStackTrace();
			return new Result<Object>(e1.getCode(), e1.getMessage(), e1.getData());
		}
	}

	@RequestMapping("get")
	public Map<?, ?> get(Long id) {
		logger.debug("" + id);
		return Utils.asMap(biz.get(id));
	}

	@RequestMapping(path = "find")
	public Page<E> find(E e, PageBean pb) {
		logger.debug(e + "");
		return biz.find(e, pb);
	}

	@RequestMapping(path = "find", consumes = MediaType.APPLICATION_JSON_VALUE)
	public Page<E> find1(@RequestBody E e, PageBean pb) {
		return find(e, pb);
	}
}
